//
//  EeRefreshHeader.swift
//  Alamofire
//
//  Created by zhuxietong on 2018/7/30.
//

import Foundation
import MJRefresh
import Eelay
//
//
//public class MoUIAdapter{
//    public static var safeInset:UIEdgeInsets{
//        get{
//            var back:UIView? = UIApplication.shared.keyWindow
//            if back == nil{
//                back = UIApplication.shared.keyWindow?.rootViewController?.view
//            }
//            if #available(iOS 11.0, *) {
//                return back?.safeAreaInsets ?? .zero
//            } else {
//                return .zero
//                // Fallback on earlier versions
//            }
//        }
//    }
//    
//    public static func bottom(_ distance:CGFloat) ->CGFloat{
//        let b = MoUIAdapter.safeInset.bottom
//        return max(b,distance)
//    }
//}
//
fileprivate let indicatorSize:CGFloat = 22


extension MJRefreshComponent{
    public class Style: NSObject {
        public static var _share:Style? = nil
        public static var share:Style{
            get{
                guard let instance = Style._share else {
                    let instance = Style()
                    Style._share = instance
                    return instance
                }
                return instance
            }
        }
        public var mode:ThemeMode{
            get{
                return MoTheme.global.mode
            }
        }
        public func dycolor(lColor:UIColor,dColor:UIColor) -> UIColor {
            switch mode {
            case .auto:
                return .color(lColor: lColor, dColor: dColor)
            case .dark:
                return dColor
            case .light:
                return lColor
            }
        }
        
        public var color:UIColor = .color(lColor: UIColor(shex: "#8888"), dColor: UIColor(shex: "#fff9"))
        public var inset = UIEdgeInsets.zero
        public var height = MJRefreshHeaderHeight
    }

}


class DefaultMJRefreshHeader: MJRefreshHeader {
    public var style = Style()
}


open class EeRefreshHeader: MJRefreshHeader {
    public var style = Style(){
        didSet{
            loadingView.color = style.color
        }
    }
  
    
//    public static var indicatorColor = UIColor(shex: "#aaaaaa88")
    
    
    let loadingView = EeRefreshIndicator()
    
    
    
    override open func prepare() {
        super.prepare()
        loadingView.frame = CGRect(x: 0, y: 0, width: indicatorSize, height: indicatorSize)
        addSubview(loadingView)
        loadingView.arcLayer.strokeEnd = 0
        mj_h = style.height + style.inset.top + style.inset.bottom
        
//        let ht = MJRefreshHeaderHeight
//        let h = ht/2.0 - indicatorSize/2.0
//        eelay = [
//            [loadingView,[ee.X.T,ee.X.B,[0,-h]],"\(indicatorSize)",indicatorSize],
//        ]
    }
    
  
    override open var pullingPercent: CGFloat{
        set{
            switch self.state {
            case .idle:
                if newValue <= 0
                {
                    return
                }
                let radio = (newValue - 0.5) * 2
                loadingView.drawLineAnimationWithRatio(ratio: radio)

//                if newValue >= 0.3
//                {
//                    loadingView.drawLineAnimationWithRatio(ratio: (newValue-0.3) * 1.5)
//                }
//                loadingView.drawLineAnimationWithRatio(ratio: newValue)
            default:
                break
            }
            super.pullingPercent = newValue

            
        }
        get{
            return super.pullingPercent
        }
    }
    

    
    func setState(state:MJRefreshState) {
    }
    
    

    override open var state: MJRefreshState{
        set{
            if state == newValue{
                return
            }
            
//            /** 普通闲置状态 */
//            MJRefreshStateIdle = 1,
//            /** 松开就可以进行刷新的状态 */
//            MJRefreshStatePulling,
//            /** 正在刷新中的状态 */
//            MJRefreshStateRefreshing,
//            /** 即将刷新的状态 */
//            MJRefreshStateWillRefresh,
//            /** 所有数据加载完毕，没有更多的数据了 */
//            MJRefreshStateNoMoreData
            
            print("new state:\(newValue.rawValue), old state:\(state.rawValue)")
            switch newValue {
            case .idle:
                weak var wself = self
                switch state {
                case .refreshing:
//                    doZorePercent()
                    wself?.loadingView.removeAnimations()
                    print(loadingView.arcLayer.animationKeys() ?? [])

                    wself?.loadingView.alpha = 1
                    co_delay(delay: 0.25) {
                        wself?.loadingView.resetShapLayer()
                    }


                    UIView.animate(withDuration: TimeInterval(MJRefreshSlowAnimationDuration), animations: {
                        wself?.loadingView.alpha = 0
                    }) { (finished) in
                        wself?.loadingView.removeAnimations()

                        wself?.loadingView.alpha = 1
                    }
                default:
                    wself?.loadingView.removeAnimations()
                }
                
            case .pulling:
                loadingView.alpha = 1
            case .refreshing:
                loadingView.alpha = 1
                loadingView.startAnimation()
            case .willRefresh:
                break
            case .noMoreData:
                break
            default:
                break
            }
            super.state = newValue
        }
        get{
            return super.state
        }
    }
    
    override open func placeSubviews() {
        super.placeSubviews()
        _ = MJRefreshHeaderHeight
//        let h = ht/2.0 - indicatorSize/2.0
//        let y = self.mj_y * 0.5
        let x = self.mj_w * 0.5
        
//        loadingView.frame = CGRect(x: 0, y: 0, width: indicatorSize, height: indicatorSize)

//        print("============s=s---|\(self.frame)")
        let y = MJRefreshHeaderHeight/2.0
        loadingView.center = CGPoint(x: x, y: y + style.inset.top)
//        print("============loadingView---|\(loadingView.frame)")
    }
}

open class EeRefreshIndicator: JoView {
    
    public var arcLayer = CAShapeLayer()
    
    public var color:UIColor = MJRefreshComponent.Style.share.color{
        didSet{
            self.resetShapLayer()
        }
    }

    
    open override func didLayoutRules() {
        
        addShapeLayer()
        self.isUserInteractionEnabled = false
        self.frame = CGRect(x: 0, y: 0, width: indicatorSize, height: indicatorSize)
    }
    
    open func addShapeLayer() {
        self.arcLayer = CAShapeLayer()
        arcLayer.lineCap = CAShapeLayerLineCap.round;
        arcLayer.lineJoin = CAShapeLayerLineJoin.round;
        arcLayer.fillColor = UIColor.clear.cgColor;
        arcLayer.strokeColor = color.cgColor;
        arcLayer.lineWidth = 1.5;
        arcLayer.strokeStart = 0;
        arcLayer.strokeEnd = 0;

        layer.addSublayer(arcLayer)
    }
    
    open func resetShapLayer() {
        arcLayer.removeFromSuperlayer()
        addShapeLayer()
        adjustShapeLayerPath()
        
    }
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
                  
           super.traitCollectionDidChange(previousTraitCollection)
           if #available(iOS 13.0, *) {
               self.traitCollection.performAsCurrent {[weak self] in
                guard let ws = self else{return}
                ws.arcLayer.lineCap = CAShapeLayerLineCap.round;
                ws.arcLayer.lineJoin = CAShapeLayerLineJoin.round;
                ws.arcLayer.fillColor = UIColor.clear.cgColor;
                ws.arcLayer.strokeColor = ws.color.cgColor;
                ws.arcLayer.lineWidth = 1.5;
                ws.arcLayer.strokeStart = 0;
                ws.arcLayer.strokeEnd = 0;
               }
           }
       }
    
    
    open func adjustShapeLayerPath() {
            arcLayer.frame = self.bounds;
            let path = UIBezierPath()
            path.addArc(withCenter: CGPoint(x: frame.size.width/2.0, y: frame.size.height/2.0), radius: frame.size.width/2.0, startAngle: CGFloat(Double.pi * 0.0), endAngle: CGFloat(2*Double.pi), clockwise: true)
            arcLayer.path = path.cgPath;

    
    }
    
    open override var frame: CGRect{
        set{
            super.frame = newValue
            adjustShapeLayerPath()
        }
        get{
            return super.frame
        }
    }
    
    func drawLineAnimationWithRatio(ratio:CGFloat) {
        
        var rad = ratio
        if ratio >= 0.93
        {
            rad = 0.93
        }
        arcLayer.strokeEnd = rad
    }
    
    
    
    
//    - (void) removeAnimations {
//    [_arcLayer removeAnimationForKey:@"pulling.refresh.rotation"];
//    [_imageView.layer removeAnimationForKey:@"pulling.refresh.rotation"];
//    }

    
    func removeAnimations() {
        arcLayer.removeAnimation(forKey: "pulling.refresh.rotation")
    }
    
    func startAnimation() {
        
        arcLayer.strokeEnd = 0.93
        let anim = CABasicAnimation(keyPath: "transform.rotation.z")
        anim.fromValue = 0.0
        anim.toValue = 2.0 * Double.pi
        anim.duration = 1.0
        anim.repeatCount = Float(INT_MAX)
        arcLayer.add(anim, forKey: "pulling.refresh.rotation")
//        anim.toValue = -2.0 * Double.pi
    }
    
    
    
//    - (void) startAnimation {
//    // Remove animation first
//    [self removeAnimations];
//
//    // Add animation
//    _arcLayer.strokeEnd = 0.94;
//    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    anim.fromValue = [NSNumber numberWithFloat:0.0];
//    anim.toValue = [NSNumber numberWithFloat:2 * M_PI];
//    anim.duration = 1.0;
//    anim.repeatCount = INT_MAX;
//    [_arcLayer addAnimation:anim forKey:@"pulling.refresh.rotation"];
//    anim.toValue = [NSNumber numberWithFloat:-2*M_PI];
//    [_imageView.layer addAnimation:anim forKey:@"pulling.refresh.rotation"];
//    }
    deinit {
    }
}

